package com.yc.cloud.openai.portal.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import lombok.val;

import java.io.File;
import java.nio.file.Files;
import java.util.Base64;

public class MyFileUtils {

    public static String encodeBase64FromUrl(String url) {
        try (val response = HttpRequest.get(url).execute()) {
            return Base64.getEncoder().encodeToString(response.bodyBytes());
        }
    }

    public static void decodeAndSaveFile(String base64AudioData, String outputPath) {
        if (StrUtil.isEmpty(base64AudioData)) {
            return;
        }
        //String outputAudioFile = "/Users/jackgu/Downloads/tts.mp3";
        // 解码Base64数据
        byte[] audioData = Base64.getDecoder().decode(base64AudioData);
        // 将解码后的数据写入到音频文件
        FileUtil.writeBytes(audioData, outputPath);
    }

    public static String convertToBase64(File file) {
        try {
            // 读取文件为字节数组
            byte[] fileContent = Files.readAllBytes(file.toPath());
            // 使用Base64类编码字节数组
            return Base64.getEncoder().encodeToString(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
